package com.zixun.controller;

import com.zixun.config.WebApiConfig;
import com.zixun.model.ApplyInfo;
import com.zixun.model.User;
import com.zixun.model.information.Information;
import com.zixun.model.information.InformationComment;
import com.zixun.model.information.InformationImage;
import com.zixun.repository.ApplyInfoRepository;
import com.zixun.repository.UserRepository;
import com.zixun.repository.information.InformationCommentRepository;
import com.zixun.repository.information.InformationImageRepository;
import com.zixun.repository.information.InformationRepository;
import com.zixun.service.InformationService;
import com.zixun.service.UserService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;


@RestController
@Transactional
@RequestMapping("api/information/")
public class InformationWebApi {

    @Autowired
    InformationImageRepository informationImageRepository;

    @Autowired
    InformationRepository informationRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    InformationCommentRepository informationCommentRepository;

    @Autowired
    InformationService informationService;

    @Autowired
    UserService userService;

    @Autowired
    ApplyInfoRepository applyInfoRepository;


    /**
     * *
     *
     * @api {GET} /api/information/informationInfo 资信详情
     * @apiName informationInfo
     * @apiGroup information
     * @apiVersion 0.0.1
     * @apiDescription 资信详情
     * @apiParam {String} userId 用户编号
     * @apiParam {Integer} informationId 资信编号
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功, 2:参数错误,3:服务器异常,8:无数据, 整型】,
     * "errMsg":【错误信息, 字符串】.
     * "data":{
     * "userId":【用户编号，字符串】
     * "userName":【行家姓名,字符串】,
     * "userHeadPicture":【行家头像，字符串】,
     * "userIntroduce":【行家介绍，字符串】,
     * "content":【资信内容,字符串】,
     * "id":【编号，字符串】
     * "address":【资信地址,字符串】,
     * "price":【资信价格,整型】,
     * "images":[{
     * "name":【图片，字符串】
     * }],
     * "type":【资信类型,0:文字，1:图片,整型】,
     * "commentCount":【评论数量,整形】,
     * "comments":[{
     * "userId":【用户编号,字符串】,
     * "userName":【用户名称,字符串】,
     * "userHeadPicture":【用户头像,字符串】,
     * "id":【评论编号,整型】,
     * "content":【评论内容,字符串】,
     * "createTime":【发布时间,长整型】
     * }]
     * }
     */
    @RequestMapping("informationInfo")
    public Map informationInfo(String userId, Integer informationId) {
        Map result = new HashMap();
        Information info = informationRepository.findOne(informationId);
        User user = userRepository.findById(info.getUserId());
        Map map = new HashMap();
        map.put("userId", user.getId().toString());
        map.put("userName", user.getName());
        map.put("userHeadPicture",WebApiConfig.IMAGE_URL+user.getHeadPicture());
        map.put("address", info.getAddress());
        map.put("userIntroduce", user.getIntroduce());
        map.put("content", info.getContent());
        map.put("id", info.getId());
        if (info.getPrice() == null) {
            map.put("price", 0);
        } else {
            map.put("price", info.getPrice());
        }
        List images = new ArrayList();
        List<InformationImage> informationImages = informationImageRepository.findByInfoId(info.getId());
        for (InformationImage image : informationImages) {
            Map imageMap = new HashMap();
            imageMap.put("name", WebApiConfig.IMAGE_URL+image.getName());
            images.add(imageMap);
        }
        map.put("images", images);
        if (info.getType() == null) {
            map.put("type", 0);

        } else {
            map.put("type", info.getType());
        }
        List<InformationComment> comments = informationCommentRepository.findAllByInfoId(info.getId());
        List commentList = new ArrayList();
        for (InformationComment informationComment : comments) {
            Map commentMap = new HashMap();
            commentMap.put("content", informationComment.getContent());
            commentMap.put("createTime", informationComment.getCreateTime().getTime());
            User commentUser = userRepository.findById(informationComment.getUserId());
            commentMap.put("userName", commentUser.getName());
            commentMap.put("userHeadPicture", WebApiConfig.IMAGE_URL+commentUser.getHeadPicture());
            commentMap.put("userId", commentUser.getId().toString());
            commentMap.put("id", informationComment.getId());
            commentList.add(commentMap);
        }
        map.put("comments", commentList);
        map.put("commentCount", commentList.size());
        result.put("returnValue", 1);
        result.put("errMsg", null);
        result.put("data", map);
        return result;
    }

    /**
     * @api {GET} /api/information/informationSale 资信销售
     * @apiName informationSale
     * @apiGroup information
     * @apiVersion 0.0.1
     * @apiDescription 资信销售
     * @apiParam {String} userId 用户编号
     * @apiParam {Integer} countPerPage 分页显示数量
     * @apiParam {Integer} pageIndex	当前页码
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功, 2:参数错误,3:服务器异常,10:用户不存在, 整型】,
     * "errMsg":【错误信息, 字符串】.
     * "data":[{
     * "userId":【用户编号，字符串】
     * "userName":【行家姓名,字符串】,
     * "userHeadPicture":【行家头像，字符串】,
     * "userIntroduce":【行家介绍，字符串】,
     * "content":【资信内容】,
     * "id":【编号，整型】
     * "address":【资信地址】,
     * "price":【资信价格】,
     * "images":[{
     * "name":【图片，字符串】
     * }],
     * "type":【资信类型,0:文字，1:图片,整型】
     * }]
     */
    //@RequestMapping("informationSale")
    //public Map informationSale(String userId, Integer countPerPage, Integer pageIndex) {
    //    Map result = new HashMap();
    //    Page<Information> informations = informationRepository.findAll(new PageRequest(pageIndex - 1, countPerPage));
    //    List list = new ArrayList();
    //    for (Information info : informations) {
    //        System.out.println("userId:"+info.getUserId());
    //        User user = userRepository.findById(Integer.valueOf(info.getUserId()));
    //        Map map = new HashMap();
    //        map.put("userName", user.getName());
    //        map.put("userHeadPicture", user.getHeadPicture());
    //        map.put("address", info.getAddress());
    //        map.put("userIntroduce", user.getIntroduce());
    //        map.put("userId",user.getId().toString());
    //        map.put("id",info.getId());
    //        map.put("content", info.getContent());
    //        if(info.getPrice()==null){
    //            map.put("price",0);
    //        }else {
    //            map.put("price", info.getPrice());
    //        }
    //        List images = new ArrayList();
    //        List<InformationImage> informationImages = informationImageRepository.findByInfoId(info.getId());
    //        for (InformationImage image : informationImages) {
    //            Map imageMap = new HashMap();
    //            imageMap.put("name", image.getName());
    //            images.add(imageMap);
    //        }
    //        map.put("images", images);
    //        if(info.getType()==null){
    //            map.put("type",0);
    //
    //        }else {
    //            map.put("type", info.getType());
    //        }
    //        list.add(map);
    //    }
    //    result.put("returnValue", 1);
    //    result.put("errMsg", null);
    //    result.put("data", list);
    //    return result;
    //}
    @RequestMapping("informationSale")
    public Map informationSale(String userId, Integer countPerPage, Integer pageIndex) {
        Map<String, Object> result = new HashMap<>();
        Page<Information> informations = informationService.findPageByUserId(Integer.valueOf(userId), pageIndex, countPerPage);
        System.out.println("length:"+informations.getSize());
        if(userId==null||pageIndex==null||countPerPage==null){
            result.put("errMsg","参数错误");
            result.put("returnValue",2);
            return result;
        }
        if(!userService.isUserExist(Integer.valueOf(userId))){
            result.put("errMsg","用户不存在");
            result.put("returnValue",10);
            return result;
        }
        List list = new ArrayList();
        for (Information info : informations) {
            User user = userRepository.findById(info.getUserId());
            Map map = new HashMap();
            map.put("userName", user.getName());
            map.put("userHeadPicture", WebApiConfig.IMAGE_URL+user.getHeadPicture());
            map.put("address", info.getAddress());
            map.put("userIntroduce", user.getIntroduce());
            map.put("userId", user.getId().toString());
            map.put("id", info.getId());
            map.put("title",info.getTitle());
            map.put("content", info.getContent());
            if (info.getPrice() == null) {
                info.setPrice(0);
                informationRepository.save(info);
            }
            map.put("price", info.getPrice());
            List images = new ArrayList();
            List<InformationImage> informationImages = informationImageRepository.findByInfoId(info.getId());
            for (InformationImage image : informationImages) {
                Map imageMap = new HashMap();
                imageMap.put("name", WebApiConfig.IMAGE_URL+image.getName());
                images.add(imageMap);
            }
            map.put("images", images);
            if (info.getType() == null) {
                map.put("type",0);

            } else {
                map.put("type",info.getType());
            }
            list.add(map);
        }
        result.put("returnValue", 1);
        result.put("errMsg", null);
        result.put("data", list);
        return result;
    }


    /**
     * @api {POST} /api/information/addInformation 添加资讯
     * @apiName addInformation
     * @apiGroup information
     * @apiVersion 0.0.1
     * @apiDescription 发布资讯
     * @apiParamExample 请求参数{JSON}
     * {
     * "userId":【用户编号, 字符串】,
     * "title":【标题，字符串】,
     * "price":【价格，整形】,
     * "type":【0：文字资讯，1：图片资讯,整形】,
     * "address":【地址，字符串】,
     * "images":["image1","image2"]
     * }
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功,2:参数错误,3:服务器异常, 整型】,
     * "errMsg":【错误信息 , 字符串】,
     * }
     */
    @RequestMapping("addInformation")
    public Map addInformation(@RequestBody String data) {
        Map result = new HashMap();
        JSONObject jo = new JSONObject(data);
        String title = jo.getString("title");
        Integer price = jo.getInt("price");
        String content = jo.getString("content");
        String address = null;
        Integer type = jo.getInt("type");
        String userId = jo.getString("userId");
        if (!jo.isNull("address")) {
            address = jo.getString("address");
        }
        Information info = new Information();
        info.setUserId(Integer.valueOf(userId));
        info.setPrice(price);
        info.setTitle(title);
        info.setContent(content);
        info.setType(type);
        info.setHot(0);
        info.setIntroduce(content);
        info.setContent(content);
        info.setCreateTime(new Date());
        info.setAddress(address);
        info.setNumber(0);
        informationRepository.save(info);
        if (type == 1) {
            JSONArray imageJsonArray = jo.getJSONArray("images");
            for (int i = 0; i < imageJsonArray.length(); i++) {
                String imageName = imageJsonArray.getString(i);
                InformationImage image = new InformationImage();
                image.setInformationId(info.getId());
                image.setName(imageName);
                informationImageRepository.save(image);
            }
        }
        result.put("returnValue", 1);
        result.put("errMsg", null);
        return result;
    }
    /**
     * @api {GET} /api/information/getMyInformation 获取我的资信
     * @apiName getMyInformation
     * @apiGroup information
     * @apiVersion 0.0.1
     * @apiDescription 资信销售
     * @apiParam {String} userId 用户编号
     * @apiParam {Integer} countPerPage 分页显示数量
     * @apiParam {Integer} pageIndex	当前页码
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功, 2:参数错误,3:服务器异常,10:用户不存在, 整型】,
     * "errMsg":【错误信息, 字符串】.
     * "data":[{
     * "title":【资信标题，字符串】
     * "createTime":【创建时间,长整型】,
     * "price":【价格，整型】,
     * "number":【购买人数，整型】,
     * }
     * }
     */
    @RequestMapping("getMyInformation")
    public Map<String,Object> gettMyInformation(String userId,Integer countPerPage,Integer pageIndex){
        Map<String,Object> result = new HashMap<>();
        if(userId==null||pageIndex==null||countPerPage==null){
            result.put("errMsg","参数错误");
            result.put("returnValue",2);
            return result;
        }
        if(!userService.isUserExist(Integer.valueOf(userId))){
            result.put("errMsg","用户不存在");
            result.put("returnValue",10);
            return result;
        }
        try {
            Page<Information> informationPage =informationService.findPageByUserId(Integer.valueOf(userId),pageIndex,countPerPage);
            List list =new ArrayList();
            for(Information information:informationPage){
                Map<String,Object> map = new HashMap();
                map.put("title",information.getTitle());
                if(information.getPrice()==null){
                    information.setPrice(0);
                    informationRepository.save(information);
                }
                map.put("price",information.getPrice());
                map.put("createTime",information.getCreateTime().getTime());
                if(information.getNumber()==null){
                    information.setNumber(0);
                    informationRepository.save(information);
                }
                map.put("number",information.getNumber());
                list.add(map);
            }
            result.put("errMsg","成功");
            result.put("returnValue",1);
            result.put("data",list);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("errMsg","服务器异常");
            result.put("returnValue",3);
            return result;
        }
    }

    /**
     * @api {GET} /api/information/searchInformationByTitle 搜索资信
     * @apiName searchInformationByTitle
     * @apiGroup information
     * @apiVersion 0.0.1
     * @apiDescription 搜索资信
     * @apiParam {String} name 标题名字
     * @apiParam {Integer} countPerPage 分页显示数量
     * @apiParam {Integer} pageIndex	当前页码
     * @apiSuccessExample 返回值: HTTP/1.1 200 OK
     * {
     * "returnValue":【1:成功, 2:参数错误,3:服务器异常, 整型】,
     * "errMsg":【错误信息, 字符串】.
     * "data":[{
     * "userId":【用户编号，字符串】
     * "userName":【行家姓名,字符串】,
     * "userHeadPicture":【行家头像，字符串】,
     * "userIntroduce":【行家介绍，字符串】,
     * "content":【资信内容，字符串】,
     * "expertise":【专长，字符串】,
     * "id":【编号，整型】
     * "address":【资信地址,字符串】,
     * "price":【资信价格,整型】,
     * "images":[{
     * "image":【图片，字符串】
     * }],
     * "type":【资信类型,0:文字，1:图片,整型】
     * }]
     */
    @RequestMapping("searchInformationByTitle")
    public Map<String,Object> searchInformationByTitle(String name,Integer pageIndex,Integer countPerPage){
        Map<String,Object> result = new HashMap<>();
        try {
            if(name==null||pageIndex==null||countPerPage==null){
                result.put("errMsg","参数错误");
                result.put("returnValue",2);
                return result;
            }
            Page<Information> informationPage = informationService.findAllByLikeTitle(name,pageIndex,countPerPage);
            System.out.println("size:" + informationPage.getSize());
            List data = new ArrayList<>();
            for(Information information:informationPage){
                System.out.println("+++++++++");
                Map informationMap = new HashMap<>();
                informationMap.put("id",information.getId());
                informationMap.put("userId",information.getUserId().toString());
                informationMap.put("title", information.getTitle());
                informationMap.put("content",information.getContent());
                if(information.getPrice()==null){
                    information.setPrice(0);
                    informationRepository.save(information);
                }
                informationMap.put("price",information.getPrice());
                informationMap.put("address",information.getAddress());
                List images = new ArrayList();
                List<InformationImage> informationImages = informationImageRepository.findByInfoId(information.getId());
                for (InformationImage image : informationImages) {
                    Map imageMap = new HashMap();
                    imageMap.put("image", WebApiConfig.IMAGE_URL+image.getName());
                    images.add(imageMap);
                }
                informationMap.put("images", images);
                User user = userService.getUserByUserId(information.getUserId());
                informationMap.put("headPicture",WebApiConfig.IMAGE_URL+user.getHeadPicture());
                ApplyInfo applyInfo = applyInfoRepository.findByUserId(information.getUserId());
                informationMap.put("username",applyInfo.getRealName());
                informationMap.put("expertise",applyInfo.getExpertise());
                data.add(informationMap);
            }
            result.put("data",data);
            result.put("errMsg", "成功");
            result.put("returnValue",1);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("errMsg","服务器异常");
            result.put("returnValue",3);
            return result;
        }
    }

}
